package com.confinderence;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

class WebServiceTask extends AsyncTask<String, Integer, String> {

	public interface IResponseHandler {
		public void handleResponse(String response);
	}

	public static final int POST_TASK = 1;
	public static final int GET_TASK = 2;
	public static final int POST_TASK_WITH_JSON = 3;

	private static final String TAG = "WebServiceTask";

	// connection timeout, in milliseconds (waiting to connect)
	private static final int CONN_TIMEOUT = 3000;

	// socket timeout, in milliseconds (waiting for data)
	private static final int SOCKET_TIMEOUT = 5000;

	private int mTaskType = GET_TASK;
	private Context mContext = null;
	private String mProcessMessage = "Processing...";
	private IResponseHandler mHandler;

	private ArrayList<NameValuePair> mParams = new ArrayList<NameValuePair>();
	private String mJson = "";

	private ProgressDialog pDlg = null;

	public WebServiceTask(int taskType, Context context, String processMessage,
			IResponseHandler handler) {

		mTaskType = taskType;
		mContext = context;
		mProcessMessage = processMessage;
		mHandler = handler;
	}
	public void setJson(String json) {
		mJson = new String(json);
	}
	public void addNameValuePair(String name, String value) {

		mParams.add(new BasicNameValuePair(name, value));
	}
	public void addJsonObject(JSONObject jsonObj) {
		JSONArray names = jsonObj.names();
		for (int i = 0; i < names.length(); i++) {
			try {
				String key = (String) names.get(i);
				Object obj = jsonObj.get(key);
				mParams.add(new BasicNameValuePair(key, obj.toString()));
			} catch (JSONException e) {
			}
		}
	}

	private void showProgressDialog() {

		pDlg = new ProgressDialog(mContext);
		pDlg.setMessage(mProcessMessage);
		pDlg.setProgressDrawable(WallpaperManager.getInstance(mContext).getDrawable());
		pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pDlg.setCancelable(false);
		pDlg.show();

	}

	@Override
	protected void onPreExecute() {

		// hideKeyboard();
		showProgressDialog();

	}

	protected String doInBackground(String... urls) {

		String url = urls[0];
		String result = "";

		HttpResponse response = doResponse(url);

		if (response == null || response.getEntity() == null) {
			return result;
		} else {

			try {

				result = inputStreamToString(response.getEntity().getContent());

			} catch (IllegalStateException e) {
				Log.e(TAG, e.getLocalizedMessage(), e);

			} catch (IOException e) {
				Log.e(TAG, e.getLocalizedMessage(), e);
			}

		}

		return result;
	}

	@Override
	protected void onPostExecute(String response) {

		mHandler.handleResponse(response);
		pDlg.dismiss();

	}

	// Establish connection and socket (data retrieval) timeouts
	private HttpParams getHttpParams() {

		HttpParams htpp = new BasicHttpParams();

		HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
		HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);

		return htpp;
	}

	private HttpResponse doResponse(String url) {

		// Use our connection and data timeouts as parameters for our
		// DefaultHttpClient
		HttpClient httpclient = new DefaultHttpClient(getHttpParams());

		HttpResponse response = null;

		try {
			switch (mTaskType) {

				case POST_TASK :
					HttpPost httppost = new HttpPost(url);
					// Add parameters
					httppost.setEntity(new UrlEncodedFormEntity(mParams));

					response = httpclient.execute(httppost);
					break;
				case POST_TASK_WITH_JSON :
					HttpPost httpPostWithJson = new HttpPost(url);
					StringEntity se = new StringEntity(mJson);
					httpPostWithJson.setHeader("Accept", "application/json");
					httpPostWithJson.setHeader("Content-type", "application/json");
					httpPostWithJson.setEntity(se);
					response = httpclient.execute(httpPostWithJson);
					break;
				case GET_TASK :
					HttpGet httpget = new HttpGet(url);
					response = httpclient.execute(httpget);
					break;
			}
		} catch (Exception e) {

			Log.e(TAG, e.getLocalizedMessage(), e);

		}

		return response;
	}

	private String inputStreamToString(InputStream is) {

		String line = "";
		StringBuilder total = new StringBuilder();

		// Wrap a BufferedReader around the InputStream
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));

		try {
			// Read response until the end
			while ((line = rd.readLine()) != null) {
				total.append(line);
			}
		} catch (IOException e) {
			Log.e(TAG, e.getLocalizedMessage(), e);
		}

		// Return full string
		return total.toString();
	}

}